"""Helper functions

Consists of functions to typically be used within templates, but also
available to Controllers. This module is available to templates as 'h'.
"""
# Import helpers as desired, or define your own, ie:
#from webhelpers.html.tags import checkbox, password

import socket
import string
import datetime, logging
from pylons import request
from pylons.controllers.util import redirect, redirect_to, abort
from enlargeweb.model.user import User

log = logging.getLogger(__name__) 

def is_admin_user():
	user = get_current_user()
	if user:
		attr = user.get_attr('rights')
		log.debug('User rights: %s' % attr.value)
		return attr.value == 'admin'
	else:
		log.error('No rights: User is not logged in.')
		return False

def get_current_user():
	identity = request.environ.get('repoze.who.identity')
	if not identity:
		log.error('No identity returned')
		abort(403)
	user = identity.get('auth_tkt')
	if not user:
		log.error('No auth_tkt returned')
		abort(403)
	if not isinstance(user, User):
		log.error('Identity is not an instance of User')
		abort(403)
	return user

def strToIp(ip):
	"convert decimal dotted quad string to long integer"

	hexn = ''.join(["%02X" % long(i) for i in ip.split('.')])
	return long(hexn, 16)

def ipToStr(n):
	"convert long int to dotted quad string"

	d = 256 * 256 * 256
	q = []
	while d > 0:
		m,n = divmod(n,d)
		q.append(str(m))
		d = d/256

	return '.'.join(q)

def longFromBytesArray(byte_array):
	result = long(0)
	for i in xrange(0,6):
		result = result << 8
		result += byte_array[i]
	return result

def macToStr(num):
	"""
	Convert long int to dotted quad string
	"""
	result = []

	for i in xrange(0,6):
		portion = "%02x" % (num & 0xff)
		result = [portion] + result
		num = num >> 8
	return ':'.join(result)

def strToMac(str_mac):
	"""
	Convert MAC in its string form to ulong representation
	"""
	result = 0
	octets = map(
		lambda x: int(x),
		filter(
			lambda x: x.isdigit() and int(x) < 256,
			str_mac.split(':')
		)
	)
	if len(octets) != 6:
		return None

	for o in octets:
		result = int(o)
		result = result << 8
	return result

def macToStr_2(n):
	"convert long int to dotted quad string"

	d = 256 * 256 * 256 * 256 * 256
	q = []
	while d > 0:
		m,n = divmod(n,d)
		q.append("%02x" % m)
		d = d/256

	return ':'.join(q)

def makeMask(n):
	"return a mask of n bits as a long integer"

	return (long(2)**n)-1

def prepareIp4Addr(ip_str):
	"""
	Validate IPv4 Addr
	"""
	if type(mac_str) != str:
		return None

	if len(ip_str) > 15:
		return None

	octets = ip_str.split('.')
	if len(octets) != 4:
		return None

	for o in octets:
		if not o.isdigit():
			return None
		if int(o) > 255:
			return None

	return ip_str

def prepareMacAddr(mac_str):
	"""
	Validate Mac Addr
	"""
	if type(mac_str) != str:
		return None

	if len(mac_str) > 17:
		return None

	octets = mac_str.split(':')
	if len(octets) != 6:
		return None

	for o in octets:
		if len(filter(lambda x: x in string.hexdigits, o)) != len(o):
			return None
		if int(o, 16) > 255:
			return None

	return mac_str.lower()

